package net.csdn.business.mirror.enums;

import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.csdn.business.mirror.service.ThirdApi;
import net.csdn.business.mirror.service.impl.thirdapi.GiteeApiImpl;
import net.csdn.business.mirror.service.impl.thirdapi.GithubApiImpl;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Objects;

public class UserTokenEnum {

    @Getter
    @AllArgsConstructor
    public enum Type {
        GITHUB(0, GithubApiImpl.class, "GitHub", "https://github.com/", true),
        GITEE(1, GiteeApiImpl.class, "Gitee", "https://gitee.com/", false),
        ;

        private int code;
        private Class<? extends ThirdApi> thirdApiService;
        private String name;
        private String baseUrl;
        private boolean abroad;

        public static final Map<Integer, Type> MAP = Maps.newHashMap();

        static {
            for (Type type : Type.values()) {
                MAP.put(type.code, type);
            }
        }

        public static Type parse(Integer code) {
            if (Objects.isNull(code) || code < 0) {
                return null;
            }
            return MAP.get(code);
        }

        public static Type parseUrl(String url) {
            if (StringUtils.isEmpty(url)) {
                return null;
            }
            for(Map.Entry<Integer, Type> entry: MAP.entrySet()) {
                if (url.startsWith(entry.getValue().baseUrl)) {
                    return MAP.get(entry.getKey());
                }
            }
            return null;
        }

        public static boolean exists(Integer code) {
            Type t = parse(code);
            return Objects.nonNull(t);
        }
    }
}
